package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

/**
 * Servlet implementation class EditUserDetails
 */
public class EditUserDetails extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
	       
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
				
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String first_name = request.getParameter("first_name");
		String last_name = request.getParameter("last_name");
		String phone_number = request.getParameter("phone_number");
				
		// TODO: more checking here 
		if (username     == null || 
			password     == null ||
			first_name   == null ||
			last_name    == null ||
			phone_number == null)
		{
			    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "some missing parameter");
				return;
						
		}
		
		if (!request.getSession(false).getAttribute("name").equals(username)) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;			
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
					"UPDATE users SET password=?, first_name=?, last_name=?, phone_number=? " +
					"WHERE username=?");
			
			
			int i = 1;
			stmnt.setString(i++, password);
			stmnt.setString(i++, first_name);
			stmnt.setString(i++, last_name);
			stmnt.setString(i++, phone_number);
			stmnt.setString(i++, username);
			stmnt.executeUpdate();		
			
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Error");
			return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		response.sendRedirect("index.jsp");		
	}

	

}
